<?php
// +----------------------------------------------------------------------
// | TwoThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.twothink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: wapai  <http://www.twothink.cn>
// +----------------------------------------------------------------------

namespace app\home\controller;
use app\admin\validate\Model;
use app\common\model\Student;
use app\home\model\Appointment;
use app\home\model\Document;
use app\user\api\HomeApi;
use app\user\api\UserApi;
use think\Cookie;
use think\Db;
use think\Loader;
use think\Session;

/**
 * 用户控制器
 * 包括用户中心，用户登录及注册
 */
class User extends Home {

    /**
     *未登录允许访问的action
     */
    protected $allowActions=[
        'register',
        'login',
        'cookieError'
        ];

    /**
     * 前置操作，验证用户权限
     */
    protected $beforeActionList=['check_user'];
    protected function check_user(){
        if(!is_login()) {//如果未登陆
            $action = request()->action();
            if(!in_array($action,$this->allowActions)){//如果未在允许列表
                $this->error("请先登陆！",'login');
            }
        }
    }

	/* 用户中心首页 */
	public function index(){
		
	}

	/* 注册页面 */
	public function register($username = '', $password = '', $repassword = '', $email = '',$mobile="", $verify = ''){
        if(!config('user_allow_register')){
            $this->error('注册已关闭');
        }

		if($this->request->isPost()){ //注册用户
			/* 检测验证码 */
		   if(!captcha_check($verify)){
                $this->error('验证码输入错误！');
            }

			/* 检测密码 */
			if($password != $repassword){
				$this->error('密码和重复密码不一致！');
			}
			/* 调用注册接口注册用户 */
            $User = new HomeApi();
			$uid = $User->register($username, $password,$email, $mobile);
			if(0 < $uid){
			    //注册成功
                $user = array('uid' => $uid, 'nickname' => $username,"mobile"=>$mobile,'status' => 1);
                if(!\think\Db::name('MemberDetail',[],false)->insert($user)){
                    $this->error('注册失败！');
                } else {
                    $this->success("成功注册！",url('login'));
                }
			} else { //注册失败，显示错误信息
				$this->error($uid);
			}

		} else { //显示注册表单
			return $this->fetch();
		}
	}

	/* 登录页面 */
	public function login($username = '', $password = '', $verify = '',$remeberUser=""){
		if($this->request->isPost()){ //登录验证
			/* 检测验证码 */
//		    if(!captcha_check($verify)){
//                $this->error('验证码输入错误！');
//            }

			/* 调用UC登录接口登录 */
			$user = new HomeApi();
			$uid = $user->login($username, $password);
			 
			if(0 < $uid){ //UC登录成功
				/* 登录用户 */
				$Member = model('MemberDetail');
				if($Member->login($uid)){ //登录用户
//                    记住用户名
                    if($remeberUser=="true"){
                        $str=think_encrypt($username,config("data_auth_key"),30*60*60*24);
                        Cookie::set('userName',$str,["expire"=>30*60*60*24]);
                    }

					//TODO:跳转到登录前页面
					$this->success('登录成功！',url('Home/Index'));
				} else {
					$this->error($Member->getError());
				}

			} else { //登录失败
				switch($uid) {
					case -1: $error = '用户不存在或被禁用！'; break; //系统级别禁用
					case -2: $error = '密码错误！'; break;
					default: $error = '未知错误！'; break; // 0-接口参数错误（调试阶段使用）
				}
				$this->error($error);
			}

		} else { //显示登录表单
            //验证是否记住
            if(Cookie::has("userName")){
                $this->assign("username",think_decrypt(Cookie::get("userName")));
            }
            //            验证是否登陆
            if(is_login()){
                $this->success("你已经登陆！",url("index/index"));
            }
            return $this->fetch();
		}
	}

	/* 退出登录 */
	public function logout(){
		if(is_login()){
			model('MemberDetail')->logout();
			$this->success('退出成功！', url('User/login'));
		} else {
			$this->redirect('User/login');
		}
	}

    /**
     * 修改密码提交
     * @author wapai   邮箱:wapai@foxmail.com
     */
    public function profile(){
        if ($this->request->isPost()) {
            //获取参数
            $uid        =   is_login();
            $data = input('param.'); 
            $password   =  $data['old'];;
            $repassword = $data['repassword'];
            $data['password'] = $data['password'];
            empty($password) && $this->error('请输入原密码');
            empty($data['password']) && $this->error('请输入新密码');
            empty($repassword) && $this->error('请输入确认密码');

            if($data['password'] !== $repassword){
                $this->error('您输入的新密码与确认密码不一致');
            }

            $Api = new HomeApi();
            $res = $Api->updateInfo($uid, $password, $data);
            if($res['status']){
                $this->success('修改密码成功！');
            }else{
                $this->error($res['info']);
            }
        }else{
		    $this->getMenu();
            return $this->fetch();
        }
    }
    /**
     *
     * cookie错误
     */
    public function cookieError(){
        $this->error("为了成功登陆请开启cookie！<br><a href='http://jingyan.baidu.com/article/4853e1e5146e071909f726e5.html' target='_blank'>点我获取帮助！</a>",null,"",6);
    }



    /**
     * 修改个人信息
     *@author yuyifade
     */
    public function edit(){
        if(request()->isPost()){
            /*获取用户名*/
           $nickname=Session::get("user_auth")['username'];
            $data=request()->post();
            $detailInfo=[
                "true_name"=>$data['true_name'],
                "sex"=>$data['sex'],
                "id_number"=>$data['id_number'],
                "school"=>$data['school'],
                "mobile"=>$data["mobile"]
            ];
            $validate = Loader::validate('MemberDetail');
            if(!$validate->check($detailInfo)){
                $this->error($validate->getError());
            }


            $res=Db::name('member_detail')->where("nickname",$nickname)->update($detailInfo);
            if($res)
                $this->success("修改成功！","index/index");
            else
                $this->error("修改失败！");

        }
        else
        {
            $studentName=$_SESSION['jiajiao_home']['user_auth']['username'];
            if(check_str_exist('member_detail','nickname',$studentName)){//判断id是否存在
                $studentDetailInfo=Db::name('member_detail')->where('nickname',$studentName)->find();
            }
            else{
                $this->error("信息错误！","index/index");
            }
            $this->assign('detailInfo',$studentDetailInfo);
            $this->getMenu();
            return $this->fetch();
        }
    }

    /**
     * 提交预约订单页面
     * @param char $teacher 教师文档id
     * @return fetch
     */
    public function appointment($teacher){
        if($teacher){
            $teacher = Model('Document')->detail($teacher);
            $this->assign('info',$teacher);
            $this->getMenu();
            return $this->fetch();
        }
        else
            return $this->error('错误的参数');
    }

    /**
     * 订单处理后台
     */
    public function order_add(){
        $uid = $_SESSION['jiajiao_home']['user_auth']['uid'];
        $appointment = Model('Appointment');
        $result = $appointment->create_order($uid,input('teacher_id'),input('date'));
        if(is_numeric($result))
            return $this->success("提交订单成功",url('index/index'));
        else
            return $this->error($result);
    }

    /**
     * 订单列表页
     */
    public function order_list(){
        $this->getMenu();
        $uid = $_SESSION['jiajiao_home']['user_auth']['uid'];
        $lists = Model('Appointment')->lists($uid);
        $this->assign('lists',$lists);
        return $this->fetch();
    }

    /**
     * 订单详情页
     */
    public function order_detail($uid){
        $this->getMenu();
        $sid = $_SESSION['jiajiao_home']['user_auth']['uid'];
        $lists = Model('Appointment')->order_detail($sid,$uid);
        $this->assign('lists',$lists);
        return $this->fetch();
    }

    /**
     * 取消订单
     */
    public function order_cancel(){
        $uid = input('uid');
        $sid = $_SESSION['jiajiao_home']['user_auth']['uid'];
        if(empty($uid))
            return $this->error('无订单信息',url('user/order_list'));
        $order = Model('Appointment')->order_cancel($sid,$uid);
        if($order)
            return $this->success('已取消订单',url('user/order_list'));
        else
            return $this->error("预约时间的原因不允许修改",url('user/order_list'));
    }
}

